import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
const routes = [
    {
        path: '/',
        name: 'Home',
        component: () => import('../views/user/Home.vue')
    },
    {
        path: '/search',
        name: 'Search',
        component: () => import('../views/user/Search.vue')
    },
    {
        path: '/property/:id',
        name: 'PropertyDetail',
        component: () => import('../views/user/PropertyDetail.vue')
    },
    {
        path: '/booking/:id',
        name: 'Booking',
        component: () => import('../views/user/Booking.vue'),

    },
    {
        path: '/orders',
        name: 'Orders',
        component: () => import('../views/user/Orders.vue'),

    },
    {
        path: '/favorites',
        name: 'Favorites',
        component: () => import('../views/user/Favorites.vue'),

    },
    {
        path: '/reviews',
        name: 'Reviews',
        component: () => import('../views/user/Reviews.vue'),

    },
    {
        path: '/profile',
        name: 'Profile',
        component: () => import('../views/user/Profile.vue'),

    },
    {
        path: '/login',
        name: 'LoginRegister',
        component: () => import('../views/user/LoginRegister.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})


// === 全局前置守卫 ===
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const isLoggedIn = userStore.isLoggedIn; // getter 会自动从持久化状态中读取

    // 如果 token 存在但 userInfo 不存在，尝试获取一次用户信息
    // 这解决了刷新页面后，userInfo 丢失的问题
    if (userStore.token && !userStore.userInfo) {
        await userStore.fetchUserInfo();
    }

    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

    if (requiresAuth && !userStore.isLoggedIn) {
        // 如果目标页面需要登录，但用户未登录，跳转到登录页
        next({ name: 'LoginRegister', query: { redirect: to.fullPath } }); // 保存用户想去的页面
    } else if (to.name === 'LoginRegister' && userStore.isLoggedIn) {
        // 如果用户已登录，还想访问登录页，直接让他去首页
        next({ name: 'Home' });
    } else {
        // 其他情况正常放行
        next();
    }
});

export default router


